package com.linkgie.galaxyframework.httpproxy.converters;

import com.linkgie.galaxyframework.httpproxy.ResponseConverter;
import com.linkgie.galaxyframework.httpproxy.ResponseHandler;
import com.linkgie.galaxyframework.httpproxy.ServiceInvocationContext;
import com.linkgie.galaxyframework.httpproxy.ServiceRequest;
import com.linkgie.galaxyframework.httpproxy.ServiceResponse;

/**
 * 适配器；
 * <p>
 * 将 {@link ResponseConverter} 适配为 {@link ResponseHandler}，以便兼容旧的代码；
 */

@SuppressWarnings("deprecation")
public class ResponseConverterHandlerAdapter implements ResponseHandler {

    private ResponseConverter responseConverter;

    public ResponseConverterHandlerAdapter(ResponseConverter responseConverter) {
        this.responseConverter = responseConverter;
    }

    @Override
    public Object handleResponse(ServiceRequest request, ServiceResponse response, ServiceInvocationContext serviceContext)
            throws Exception {
                // 注：默认的 ServiceRequest 实现会保持兼容旧的 ServiceRequest 接口；
        if (request instanceof com.linkgie.galaxyframework.httpproxy.core.ServiceRequest) {
            return responseConverter.getResponse((com.linkgie.galaxyframework.httpproxy.core.ServiceRequest) request,
                    response.getInputStream(), serviceContext);
        } else {
            // 无法直接转换适配时，引发异常；
            throw new IllegalStateException("The response handler can not adapt the request to the deprecated type["
                    + com.linkgie.galaxyframework.httpproxy.core.ServiceRequest.class.getName() + "]!");
        }
    }

}
